package io.gitee.zhangbinhub.acp.boot.tools

import org.springframework.core.env.MapPropertySource
import org.springframework.core.env.MutablePropertySources

object EnvironmentTools {
    @JvmStatic
    fun addOrReplaceProperty(
        propertySources: MutablePropertySources,
        propertyMap: Map<String, Any?>,
        propertySourceName: String,
        first: Boolean
    ) {
        var target: MapPropertySource? = null
        if (propertySources.contains(propertySourceName)) {
            val source = propertySources[propertySourceName]
            if (source is MapPropertySource) {
                target = source
                for (key in propertyMap.keys) {
                    if (!target.containsProperty(key)) {
                        target.source[key] = propertyMap[key]
                    }
                }
            }
        }
        if (target == null) {
            target = MapPropertySource(propertySourceName, propertyMap)
        }
        if (!propertySources.contains(propertySourceName)) {
            if (first) {
                propertySources.addFirst(target)
            } else {
                propertySources.addLast(target)
            }
        }
    }
}